package com.lijing.mock.config;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.lijing.mock.constract.LocalConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 缓存配置
 * @author by lijing
 * @date 2019/12/4 0004 15:04
 */
@Slf4j
@EnableCaching
@Component
public class CacheConfig {

    /**
     * 不使用配置文件的方式实现CacheManager
     * 方便实现多个cache 使用不同实现方式及个性化设置
     * @return spring缓存管理器
     */
    @Bean
    public CacheManager cacheManager(){
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        List<CaffeineCache> caffeineCaches = new ArrayList<>();
        Cache cache =Caffeine.newBuilder()
                .maximumSize(200)
                .expireAfterAccess(300, TimeUnit.SECONDS)
                .build();
        caffeineCaches.add(new CaffeineCache(LocalConstant.URL_RANDOM_CACHE_NAME,cache));
        cacheManager.setCaches(caffeineCaches);
        return cacheManager;
    }
}
